﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using UFIDA.U9.Base.BaseBE.BaseCommon;
using UFIDA.U9.Base.Currency;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.Base.UOM;
using UFIDA.U9.CBO.FI.CFPDTO;
using UFIDA.U9.CBO.FI.Tax;
using UFIDA.U9.CBO.SCM.FeeType;
using UFIDA.U9.CBO.SCM.InstalmentRecScheduleTemplate;
using UFIDA.U9.CBO.SCM.PickList;
using UFIDA.U9.CBO.SCM.Supplier;
using UFIDA.U9.ISV.PO;
using UFIDA.U9.ISV.PO.Proxy;
using UFIDA.U9.ISV.PUB.RestSV.Model.Pub;
using UFIDA.U9.PM.PaySchedule;
using UFIDA.U9.PM.PO;
using UFIDA.U9.PM.Pub;
using UFIDA.U9.PM.Rcv;
using UFIDA.U9.PR.PurchaseRequest;
using UFIDA.U9C.Cust.ZL.OpenAPI.PO.DTO;
using UFIDA.UBF.UMC;
using UFSoft.UBF.Business;
using UFSoft.UBF.MVC;
using UFSoft.UBF.MVC.Common;
using UFSoft.UBF.PL;
using UFSoft.UBF.PL.Engine;
using UFSoft.UBF.PL.Engine.Cache;
using UFSoft.UBF.Transactions;

namespace UFIDA.U9C.Cust.ZL.OpenAPI.PO
{
    public class CustZLPOController : OpenAPIController
    {
        /// <summary>
        /// 新增有来源采购订单
        /// </summary>
        [HttpPost]
        public ApiResult<List<ResultDTORData>> Create([FromBody] List<POSrcReqDTO> poRequestDTO)
        {
            Log.Info("SRM调用U9采购订单:" + BaseJsonHelper.GetJsonJS(poRequestDTO));
            List<ResultDTORData> returns = null;
            if (poRequestDTO == null)
            {
                returns = new List<ResultDTORData>();
                returns.Add(new ResultDTORData()
                {
                    Code = "101",
                    OtherID = string.Empty,
                    IsSucess = false
                });

                return new ApiResult<List<ResultDTORData>>()
                {
                    ResCode = 101,
                    Data = returns,
                    ResMsg = "参数为空"
                };
            }
            ApiResult<List<ResultDTORData>> ret = new ApiResult<List<ResultDTORData>>();
            List<BusinessEntity.EntityKey> createdPOS = new List<BusinessEntity.EntityKey>();
            using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
            {
                try
                {


                    CreatePOBySrcDocSVProxy proxy = new CreatePOBySrcDocSVProxy();

                    foreach (POSrcReqDTO po in poRequestDTO)
                    {
                        Currency currencyAC = Currency.FindByCode(po.ac?.Code);
                        if (currencyAC == null)
                        {
                            throw new Exception($"原币种{po.ac?.Code}不存在");
                        }
                        Currency currencyTC = Currency.FindByCode(po.tc?.Code);
                        if (currencyTC == null)
                        {
                            throw new Exception($"交易币种{po.tc?.Code}不存在");
                        }
                        Organization organization = Organization.FindByCode(po.org_code);
                        if (organization == null)
                        {
                            throw new Exception($"组织{po.org_code}不存在");
                        }
                        Supplier supplier = Supplier.Finder.Find($"Code='{po.Supplier?.Code}' and Org.ID={organization.ID}");

                        if (supplier == null)
                        {
                            throw new Exception($"供应商{po.Supplier?.Code}不在组织{organization.Name}中");
                        }
                        if (!po.POLines.Select(p => "'" + p.SrcDocPRDocNo + "'").Any())
                        {
                            throw new Exception($"请购订单未输入");
                        }
                        string prDocNos = string.Join(",", po.POLines.Select(p => "'" + p.SrcDocPRDocNo + "'"));

                        List<UFIDA.U9.PR.PurchaseRequest.PR> prList = UFIDA.U9.PR.PurchaseRequest.PR.Finder.FindAll($"DocNo in ({prDocNos})").OfType<UFIDA.U9.PR.PurchaseRequest.PR>().ToList();
                        if (!prList.Any())
                        {
                            throw new Exception($"请购单不存在");
                        }
                        PODocType podocType = PODocType.Finder.Find("Code=@code and Org=@org", new OqlParam(po.DocumentType),
                                new OqlParam(organization.ID));

                        if (podocType == null)
                        {
                            throw new Exception($"单据类型不存在{po.DocumentType}");
                        }

                        proxy = new CreatePOBySrcDocSVProxy();
                        proxy.SrcPos = new List<U9.ISV.PO.SrcPODTOData>();
                        proxy.PODocType = podocType.ID;
                        foreach (SrcPOLine poline in po.POLines)
                        {
                            U9.ISV.PO.SrcPODTOData srcPODTOData = new U9.ISV.PO.SrcPODTOData();

                            srcPODTOData.AC = currencyAC.ID;
                            srcPODTOData.TC = currencyTC.ID;

                            srcPODTOData.SrcDocOrg = organization.ID;
                            srcPODTOData.TCToACExchRate = decimal.Parse(po.TCToACExchRate);
                            try
                            {
                                srcPODTOData.SrcDocID = prList.SelectMany(p => p.PRLineList.OfType<PRLine>()).Where(p => p.PR.DocNo.Equals(poline.SrcDocPRDocNo) && p.DocLineNo == int.Parse(poline.SrcDocPRLineNo)).FirstOrDefault().ID;
                            }
                            catch
                            {
                                throw new Exception($"订单{poline.SrcDocPRDocNo}第{poline.SrcDocPRLineNo}行 不存在");
                            }
                            srcPODTOData.ItemInfo = new U9.CBO.SCM.Item.ItemInfoData();
                            srcPODTOData.ItemInfo.ItemCode = poline.ItemCode;
                            
                          
                            srcPODTOData.ToPOQty = new U9.CBO.DTOs.DoubleQuantityData();

                            srcPODTOData.ToPOQty1 = decimal.Parse(poline.reqQtyTU);
                            //srcPODTOData.ToPOQty2 = decimal.Parse(poline.reqQtyTU);
                            srcPODTOData.RequireDeliverDate = Convert.ToDateTime(poline.DeliveryDate);
                            srcPODTOData.Supplier = new SupplierMISCInfoData();
                            srcPODTOData.Supplier.Code = supplier.Code;
                            srcPODTOData.Supplier.Supplier = supplier.ID;
                            srcPODTOData.Supplier.Name = supplier.Name;

                            if (po.purOper != null)
                            {
                                srcPODTOData.PurOper = new U9.Base.DTOs.IDCodeNameDTOData();
                                srcPODTOData.PurOper.Code = po.purOper.Code;
                            }



                            srcPODTOData.FinallyPriceTC = decimal.Parse(poline.FinallyPriceTC);

                            if (srcPODTOData.FinallyPriceTC <= 0m)
                            {
                                srcPODTOData.IsPresent = true;
                            }
                              

                            srcPODTOData.TaxRate = decimal.Parse(poline.TaxRate);
                            TaxSchedule taxSchedule = TaxSchedule.Finder.Find($"Name='{poline.TaxSchedule_name}'");
                            
                            srcPODTOData.TaxSchedule = new U9.Base.DTOs.IDCodeNameDTOData();
                            srcPODTOData.TaxSchedule.Code = taxSchedule?.Code;
                            //srcPODTOData.TaxSchedule.ID = taxSchedule.ID;
                            srcPODTOData.TaxSchedule.Name = taxSchedule?.Name;
                            if (poline.DescFlexField != null)
                                srcPODTOData.DescFlexSegments = poline.DescFlexField;
                            else
                                srcPODTOData.DescFlexSegments = new U9.Base.FlexField.DescFlexField.DescFlexSegmentsData();

                            srcPODTOData.PODescFlexSegments = po.HeadDescFlexField ?? new U9.Base.FlexField.DescFlexField.DescFlexSegmentsData();
                            srcPODTOData.PODescFlexSegments.PrivateDescSeg1 = po.OtherID;
                            //制单人
                            srcPODTOData.PODescFlexSegments.PrivateDescSeg2 = po.CreateBy;
                            //srcPODTOData.
                            proxy.SrcPos.Add(srcPODTOData);
                        }

                        if (proxy.SrcPos.Count > 0)
                        {
                            proxy.SrcPR = true;
                            createdPOS.AddRange(proxy.Do());
                        }

                    }
                    scope.Commit();
                    PLCacheManager.DataCache.FlushCache();
                    PLCacheManager.ObjectCache.FlushCache();

                    if (createdPOS.Count > 0)
                    {


                        var purchases = UFIDA.U9.PM.PO.PurchaseOrder.Finder.FindAll($"ID in ({string.Join(",", createdPOS.Select(p => p.ID))})").OfType<PurchaseOrder>();

                        if (purchases.Any())
                        {
                            CreatePickList(createdPOS, poRequestDTO, purchases.ToList());
                            CreateFees(createdPOS, poRequestDTO, purchases.ToList());

                            CreatePaymentSchedule(createdPOS, poRequestDTO, purchases.ToList());
                        }


                        UFIDA.U9.ISV.PO.Proxy.ApprovePOISVProxy approvePOISVProxy = new ApprovePOISVProxy();

                        approvePOISVProxy.POList = new List<U9.Base.DTOs.IDCodeNameDTOData>();
                        approvePOISVProxy.ActionType = 8;
                        foreach (PurchaseOrder po in purchases)
                        {
                            approvePOISVProxy.POList.Add(new U9.Base.DTOs.IDCodeNameDTOData { ID = po.ID });
                        }
                        approvePOISVProxy.Do();

                        returns = new List<ResultDTORData>();
                        foreach (PurchaseOrder result in purchases)
                        {
                            returns.Add(new ResultDTORData()
                            {
                                Code = result.DocNo,
                                OtherID = poRequestDTO[0].OtherID,
                                IsSucess = true
                            });
                        }
                        return new ApiResult<List<ResultDTORData>>()
                        {
                            ResCode = 0,
                            Data = returns,
                            ResMsg = "成功"
                        };//返回，不执行 scope.Commit();就会回滚
                    }
                    else
                    {
                        throw new Exception("采购订单数量为0");
                    }






                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    scope.Rollback();
                    returns = new List<ResultDTORData>();
                    returns.Add(new ResultDTORData()
                    {
                        Code = "201",

                        IsSucess = false
                    });

                    return new ApiResult<List<ResultDTORData>>()
                    {
                        ResCode = 201,
                        Data = returns,
                        ResMsg = ex.StackTrace + ex.Message
                    };//返回，不执行 scope.Commit();就会回滚
                }
                //scope.Commit();





            }
        }

        /// <summary>
        /// 修改采购订单
        /// </summary>
        /// <param name="poModifyReqDTO">接口参数</param>
        /// <returns></returns>
        public ApiResult<List<ResultDTORData>> ModifyPO([FromBody] List<POModifyReqDTO> poModifyReqDTO)
        {
            List<ResultDTORData> returns = null;
            if (poModifyReqDTO == null)
            {
                returns = new List<ResultDTORData>();
                returns.Add(new ResultDTORData()
                {
                    Code = "101",
                    OtherID = string.Empty,
                    IsSucess = false
                });

                return new ApiResult<List<ResultDTORData>>()
                {
                    ResCode = 101,
                    Data = returns,
                    ResMsg = "参数为空"
                };
            }
            ApiResult<List<ResultDTORData>> ret = new ApiResult<List<ResultDTORData>>();

            using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
            {
                try
                {
                    string poOtherIds = string.Join(",", poModifyReqDTO.Select(p => "'" + p.OtherID + "'"));
                    IEnumerable<PurchaseOrder> orders = PurchaseOrder.Finder.FindAll($"DescFlexField.PrivateDescSeg1 in ({poOtherIds})");
                    if (orders.Any())
                    {
                        ModifyPODoc(orders, poModifyReqDTO);

                        PLCacheManager.DataCache.FlushCache();
                        PLCacheManager.ObjectCache.FlushCache();

                        //收货单改价
                        ModifyReceiveDoc(orders, poModifyReqDTO);


                        scope.Commit();

                    }

                    returns = new List<ResultDTORData>();
                    foreach (PurchaseOrder order in orders)
                    {
                        returns.Add(new ResultDTORData
                        {
                            Code = order.DocNo,
                            ID = order.ID,
                            OtherID = order.DescFlexField.PrivateDescSeg1


                        });
                    }

                    return new ApiResult<List<ResultDTORData>>()
                    {
                        ResCode = 0,
                        Data = returns,
                        ResMsg = "成功"
                    };//返回，不执行 scope.Commit();就会回滚


                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    scope.Rollback();
                    returns = new List<ResultDTORData>();
                    returns.Add(new ResultDTORData()
                    {
                        Code = "201",

                        IsSucess = false
                    });

                    return new ApiResult<List<ResultDTORData>>()
                    {
                        ResCode = 201,
                        Data = returns,
                        ResMsg = ex.StackTrace + ex.Message
                    };//返回，不执行 scope.Commit();就会回滚
                }
                //scope.Commit();




            }
        }

        private void CreatePickList(List<BusinessEntity.EntityKey> createdPOS, List<POSrcReqDTO> poRequestDTO, List<UFIDA.U9.PM.PO.PurchaseOrder> purchases)
        {
            if (createdPOS != null && createdPOS.Count > 0)
            {
                using (UFSoft.UBF.Business.ISession session = UFSoft.UBF.Business.Session.Open())
                {
                    foreach (POSrcReqDTO po in poRequestDTO)
                    {
                        var temps = po.POLines.Select(p => new { DocNo = p.SrcDocPRDocNo, DocLine = p.SrcDocPRLineNo });
                        PurchaseOrder purchaseOrder = purchases.Where(p => p.POLines.OfType<POLine>().Where(t =>
                        temps.Where(m => m.DocNo.Equals(t.SrcDocInfo.SrcDocNo) && int.Parse(m.DocLine) == t.SrcDocInfo.SrcDocLineNo).Any()
                        ).Any()).FirstOrDefault();
                        if (purchaseOrder != null)
                        {
                            //委外 只有委外才有备料
                            if (purchaseOrder.DocumentType.Code.Equals("PO14"))
                            {
                                foreach (var poline in purchaseOrder.POLines.OfType<POLine>().ToList())
                                {
                                    PicKHead pickHead = PicKHead.Create();
                                    pickHead.POLine = poline;
                                    SrcPOLine srcPOLine = po.POLines.Where(p => p.SrcDocPRDocNo.Equals(poline.SrcDocInfo.SrcDocNo) && int.Parse(p.SrcDocPRLineNo) == poline.SrcDocInfo.SrcDocLineNo).FirstOrDefault();

                                    if (srcPOLine != null)
                                    {
                                        foreach (var item in srcPOLine.osInfo)
                                        {
                                            SCMPickList pickList = SCMPickList.Create(pickHead);
                                            pickList.ItemInfo = new U9.CBO.SCM.Item.ItemInfo();
                                            pickList.ItemInfo.ItemCode = item.ItemCode;
                                            pickList.PickLineNo = int.Parse(item.PickLineNo);
                                            pickList.ActualReqQty = decimal.Parse(item.ActualReqQty);

                                            pickList.IssueUOM = UOM.FindByCode(item.IssueUOM);
                                            pickList.SupplyOrg = Organization.FindByCode(item.SupplyOrg);
                                            pickList.PlanReqDate = Convert.ToDateTime(item.PlanReqDate);
                                        }

                                    }

                                }
                            }
                        }
                    }

                    session.Commit();
                }
            }
        }

        private void CreateFees(List<BusinessEntity.EntityKey> createdPOS, List<POSrcReqDTO> poRequestDTO, List<UFIDA.U9.PM.PO.PurchaseOrder> purchases)
        {
            if (createdPOS != null && createdPOS.Count > 0)
            {
                using (UFSoft.UBF.Business.ISession session = UFSoft.UBF.Business.Session.Open())
                {
                    foreach (POSrcReqDTO po in poRequestDTO)
                    {


                        var temps = po.POLines.Select(p => new { DocNo = p.SrcDocPRDocNo, DocLine = p.SrcDocPRLineNo });
                        PurchaseOrder purchaseOrder = purchases.Where(p => p.POLines.OfType<POLine>().Where(t =>
                        temps.Where(m => m.DocNo.Equals(t.SrcDocInfo.SrcDocNo) && int.Parse(m.DocLine) == t.SrcDocInfo.SrcDocLineNo).Any()
                        ).Any()).FirstOrDefault();
                        if (purchaseOrder != null)
                        {

                            foreach (var poline in purchaseOrder.POLines)
                            {
                                SrcPOLine srcPOLine = po.POLines.Where(p => p.SrcDocPRDocNo.Equals(poline.SrcDocInfo.SrcDocNo) && int.Parse(p.SrcDocPRLineNo) == poline.SrcDocInfo.SrcDocLineNo).FirstOrDefault();
                                if (srcPOLine != null)
                                {
                                    foreach (var fee in srcPOLine.orderDetailPrices)
                                    {
                                        POFee poFee = POFee.Create(poline);

                                        poFee.FeeType = PurchaseFeeType.Finder.Find($"Code='{fee.item_no}'");
                                        poFee.FeeIncludeTaxFeeC = decimal.Parse(fee.amount);
                                    }

                                }
                            }

                        }
                    }

                    session.Commit();

                }
            }
        }
        private void CreatePaymentSchedule(List<BusinessEntity.EntityKey> createdPOS, List<POSrcReqDTO> poRequestDTO, List<UFIDA.U9.PM.PO.PurchaseOrder> purchases)
        {

            using (UFSoft.UBF.Business.ISession session = UFSoft.UBF.Business.Session.Open())
            {
                foreach (POSrcReqDTO po in poRequestDTO)
                {
                    if (po.poStages.Any())
                    {
                        var temps = po.POLines.Select(p => new { DocNo = p.SrcDocPRDocNo, DocLine = p.SrcDocPRLineNo });
                        PurchaseOrder purchaseOrder = purchases.Where(p => p.POLines.OfType<POLine>().Where(t =>
                        temps.Where(m => m.DocNo.Equals(t.SrcDocInfo.SrcDocNo) && int.Parse(m.DocLine) == t.SrcDocInfo.SrcDocLineNo).Any()
                        ).Any()).FirstOrDefault();
                        if (purchaseOrder != null)
                        {

                            PaymentSchedule paymentSchedule = PaymentSchedule.Create();
                            paymentSchedule.SrcDocNo = purchaseOrder.DocNo;
                            paymentSchedule.SrcDocID = purchaseOrder.ID;
                            paymentSchedule.Org = purchaseOrder.Org;
                            foreach (var scheduleline in po.poStages)
                            {

                                PaymentScheduleLine paymentScheduleLine = PaymentScheduleLine.Create(paymentSchedule);
                                paymentScheduleLine.InstalmentType = InstalmentTypeEnum.GetFromName(scheduleline.stage_name);
                                paymentScheduleLine.Remark = scheduleline.stage_remark;
                                paymentScheduleLine.ActualReceiveMoney = decimal.Parse(scheduleline.payment_amount);
                            }
                        }
                        session.Commit();
                    }

                }

            }


        }

        private void ModifyReceiveDoc(IEnumerable<UFIDA.U9.PM.PO.PurchaseOrder> purchases, List<POModifyReqDTO> poModifyReqDTO)
        {
            if (purchases.Any())
            {
                using (UFSoft.UBF.Business.ISession session = UFSoft.UBF.Business.Session.Open())
                {
                    foreach (PurchaseOrder po in purchases)
                    {
                        foreach (POLine poline in po.POLines)
                        {
                            var changedLine = poModifyReqDTO.Where(p => p.OtherID.Equals(po.DescFlexField.PrivateDescSeg1)).SelectMany(p => p.modifylines).Where(p => p.ItemCode.Equals(poline.ItemInfo.ItemCode)).FirstOrDefault();
                            if (changedLine != null)
                            {

                                var changedHead = poModifyReqDTO.Where(p => p.OtherID.Equals(po.DescFlexField.PrivateDescSeg1)).FirstOrDefault();
                                RcvLine rcvLine = RcvLine.Finder.Find($"SrcDoc.SrcDocLine.EntityID={poline.ID}");
                                if (changedHead.IsPriceIncludeTax)
                                {
                                    if (changedLine.FinallyPriceTC > 0)
                                    {
                                        rcvLine.FinallyPriceTC = changedLine.FinallyPriceTC;
                                    }
                                    if (changedLine.Qty > 0)
                                    {
                                        rcvLine.ArriveQtyPU = changedLine.Qty;
                                    }

                                    rcvLine.FinallyPriceAC = rcvLine.FinallyPriceTC;
                                    rcvLine.ArriveTotalMnyTC = changedLine.FinallyPriceTC * rcvLine.ArriveQtyPU;
                                    rcvLine.ArriveTotalNetMnyTC = (rcvLine.FinallyPriceTC * rcvLine.ArriveQtyPU) / (1 + changedHead.TaxRate);
                                    rcvLine.ArriveTotalTaxTC = rcvLine.ArriveTotalMnyTC - rcvLine.ArriveTotalNetMnyTC;
                                }
                                else
                                {
                                    if (changedLine.FinallyPriceTC > 0)
                                    {
                                        rcvLine.FinallyPriceTC = changedLine.FinallyPriceTC;
                                    }
                                    if (changedLine.Qty > 0)
                                    {
                                        rcvLine.ArriveQtyPU = changedLine.Qty;
                                    }
                                    rcvLine.FinallyPriceTC = changedLine.FinallyPriceTC;
                                    rcvLine.FinallyPriceAC = rcvLine.FinallyPriceTC;
                                    rcvLine.ArriveTotalMnyTC = rcvLine.FinallyPriceTC * rcvLine.ArriveQtyPU * (1 + changedHead.TaxRate);
                                    rcvLine.ArriveTotalNetMnyTC = rcvLine.FinallyPriceTC * rcvLine.ArriveQtyPU;
                                    rcvLine.ArriveTotalTaxTC = rcvLine.ArriveTotalMnyTC - rcvLine.ArriveTotalNetMnyTC;
                                }

                                rcvLine.SysState = ObjectState.Updated;
                            }

                        }
                    }

                    session.Commit();
                }
            }
        }


        private void ModifyPODoc(IEnumerable<UFIDA.U9.PM.PO.PurchaseOrder> purchases, List<POModifyReqDTO> poModifyReqDTO)
        {

            using (UFSoft.UBF.Business.ISession session = UFSoft.UBF.Business.Session.Open())
            {


                foreach (PurchaseOrder po in purchases)
                {
                    po.SysState = ObjectState.Updated;
                    var changedPOlines = poModifyReqDTO.Where(p => p.OtherID.Equals(po.DescFlexField.PrivateDescSeg1)).FirstOrDefault()?.modifylines;
                    foreach (POLine poline in po.POLines)
                    {
                        var changedHead = poModifyReqDTO.Where(p => p.OtherID.Equals(po.DescFlexField.PrivateDescSeg1)).FirstOrDefault();

                        if (changedHead.IsPriceIncludeTax)
                        {

                            var modifyline = changedPOlines.Where(p => p.DocLineNo.Equals(poline.DocLineNo.ToString()) && p.ItemCode.Equals(poline.ItemInfo.ItemCode)).FirstOrDefault();
                            if (modifyline != null)
                            {
                                if (modifyline.Qty >= 0)
                                {
                                    poline.SupplierConfirmQtyTU = modifyline.Qty;
                                }
                                if (modifyline.FinallyPriceTC > 0)
                                {
                                    poline.FinallyPriceTC = modifyline.FinallyPriceTC;
                                }

                                poline.FinallyPriceAC = poline.FinallyPriceTC;
                                poline.TotalMnyTC = poline.FinallyPriceTC * poline.SupplierConfirmQtyTU;
                                poline.NetMnyTC = (poline.FinallyPriceTC * poline.SupplierConfirmQtyTU) / (1 + changedHead.TaxRate);
                                poline.TotalTaxTC = poline.TotalMnyTC - poline.NetMnyTC;
                            }
                        }
                        else
                        {
                            var modifyline = changedPOlines.Where(p => p.DocLineNo.Equals(poline.DocLineNo.ToString()) && p.ItemCode.Equals(poline.ItemInfo.ItemCode)).FirstOrDefault();
                            if (modifyline != null)
                            {
                                if (modifyline.Qty >= 0)
                                {
                                    poline.SupplierConfirmQtyTU = modifyline.Qty;
                                }
                                if (modifyline.FinallyPriceTC > 0)
                                {
                                    poline.FinallyPriceTC = modifyline.FinallyPriceTC;
                                }

                                poline.FinallyPriceAC = poline.FinallyPriceTC;
                                poline.TotalMnyTC = poline.FinallyPriceTC * poline.SupplierConfirmQtyTU * (1 + changedHead.TaxRate);
                                poline.NetMnyTC = poline.FinallyPriceTC * poline.SupplierConfirmQtyTU;
                                poline.TotalTaxTC = poline.TotalMnyTC - poline.NetMnyTC;
                            }
                        }

                        poline.SysState = ObjectState.Updated;
                    }
                }

                session.Commit();
            }


        }
    }
}
